package com.zxq.modbus.dispatch;



import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import com.zxq.tcp.handler.dispatch.HandlerDispatch;

import com.zxq.modbus.container.ModBusChannelContainer;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SFModBusRegisterHandler extends HandlerDispatch {



    @Override
    public void decodeFrame() {
        in.skipBytes(2);
        //int length = in.readByte() * 256 + in.readByte();
        int length = (in.readByte() & 0xff) * 256 + (in.readByte()& 0xff);

        if (in.readableBytes() < length) {
            log.info("当前可读数据不够，继续等  待4。。");
            return ;
        }
        byte[] content = new byte[length];
        //因为读取了一个unitFlag,所以length - 1;
        if (in.readableBytes() < length ) {
            return ;
        }
        in.readBytes(content);
        String registerId = HexBin.encode(content);
        ModBusChannelContainer.putChannel(registerId,channel);
    }

    // EE FF 00 0A 01 02 03 04 05 06 07 08 09 0A
    // EEFF000A0102030405060708090A
    @Override
    public boolean isThisFrame() {
        byte primaryByte = in.readByte();
        byte secondByte = in.readByte();
        in.resetReaderIndex();
        if(primaryByte == (byte)0xEE && secondByte == ((byte)0xFF)) {
            return true;
        }
        //log.info("dph_104 不可读:"+ HexBin.encode(new byte[]{primaryByte,secondByte}));
        return false;
    }


}
